#![allow(non_snake_case)]
use crate::_binder::Binder;
use leptos::{ev, html, prelude::*};
use thaw_components::{Follower, FollowerPlacement, FollowerWidth};
#[slot]
pub struct DropdownContent {
    children: Children,
}
#[component]
pub fn Dropdown(
    #[prop(default=FollowerPlacement::BottomEnd)] placement: FollowerPlacement,
    dropdown_content: DropdownContent,
    children: Children,
) -> impl IntoView {
    let is_show_menu = RwSignal::new(false);
    let trigger_ref = NodeRef::<html::Div>::new();
    let menu_ref = NodeRef::<html::Div>::new();
    #[cfg(any(feature = "csr", feature = "hydrate"))]
    {
        use leptos::wasm_bindgen::__rt::IntoJsResult;
        let timer = window_event_listener(ev::click, move |ev| {
            if !is_show_menu.get() {
                return;
            }
            let el = ev.target();
            let el: Option<web_sys::Node> = el.into_js_result().map_or(None, |el| Some(el.into()));
            let is_descendent_of_select = trigger_ref.get().unwrap().contains(el.as_ref());
            let is_descendent_of_menu = menu_ref.get().unwrap().contains(el.as_ref());
            if (!is_descendent_of_select && !is_descendent_of_menu)
                || (is_show_menu.get() && el.unwrap() == ***trigger_ref.get().unwrap())
            {
                let menu_div = menu_ref.get().unwrap();
                let rect = menu_div.get_bounding_client_rect();
                let x = ev.x() as f64 - rect.left() - menu_div.client_left() as f64;
                let y = ev.y() as f64 - rect.top() - menu_div.client_top() as f64;
                let is_inside_menu = x >= 0.0 && x <= menu_div.offset_height() as f64 && y >= 0.0;
                if !is_inside_menu {
                    is_show_menu.set(false);
                }
            }
        });
        on_cleanup(move || timer.remove());
    }
    view! {
        <Binder>
            <div class="min-w-24 max-w-xs"
                node_ref=trigger_ref
                on:click=move|_|is_show_menu.set(true)>
                {children()}
            </div>
            <Follower
                slot
                show=is_show_menu
                placement
                width=FollowerWidth::Target
            >
                <div node_ref=menu_ref class=("hidden",move||!is_show_menu.get())>
                    {(dropdown_content.children)()}
                </div>
            </Follower>
        </Binder>
    }
}
